package com.sc.nft.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sc.nft.dao.SysRegionDao;
import com.sc.nft.entity.SysRegion;
import com.sc.nft.entity.dto.RegionLinkedDTO;
import com.sc.nft.service.SysRegionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class SysRegionServiceImpl implements SysRegionService {

    private final SysRegionDao sysRegionDao;

    private final RedisTemplate<String, String> redisTemplate;

    @Override
    public List<SysRegion> regionLinked(RegionLinkedDTO regionLinkedDTO) {
        // 组装缓存的key
        String regionLinkedKey = "";
        if (regionLinkedDTO.getTop()) {
            regionLinkedKey = StrUtil.format("regionLiregionLinkednked:{}", "-1");

            Boolean dataExist = redisTemplate.hasKey(regionLinkedKey);
            if (Objects.isNull(dataExist) || dataExist) {
                return JSONObject.parseArray(String.valueOf(redisTemplate.opsForValue().get(regionLinkedKey)), SysRegion.class);
            }
            QueryWrapper<SysRegion> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("region_parent_id", "-1");
            List<SysRegion> list = sysRegionDao.list(queryWrapper);
            redisTemplate.opsForValue().set(regionLinkedKey, JSON.toJSONString(list));
            return list;
        }
        regionLinkedKey = StrUtil.format("regionLinked:{}", regionLinkedDTO.getRegionId());
        Boolean dataExist = redisTemplate.hasKey(regionLinkedKey);
        if (Objects.isNull(dataExist) || dataExist) {
            return JSONObject.parseArray(String.valueOf(redisTemplate.opsForValue().get(regionLinkedKey)), SysRegion.class);
        }
        QueryWrapper<SysRegion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("region_parent_id", regionLinkedDTO.getRegionId());
        List<SysRegion> list = sysRegionDao.list(queryWrapper);
        redisTemplate.opsForValue().set(regionLinkedKey, JSON.toJSONString(list));
        return list;
    }

}
